package com.zhiyizhen.handheld.component.message;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.PopupWindow;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.zhiyizhen.handheld.R;
import com.zhiyizhen.handheld.common.DataCache;
import com.zhiyizhen.handheld.common.RxJavaUtil;
import com.zhiyizhen.handheld.common.ToastUtil;
import com.zhiyizhen.handheld.common.event.UpdateMessageCountEvent;
import com.zhiyizhen.handheld.common.view.BaseFragment;
import com.zhiyizhen.handheld.component.login.bean.LoginBean;
import com.zhiyizhen.handheld.component.message.adapter.MessageAdapter;
import com.zhiyizhen.handheld.component.message.api.IMessageService;
import com.zhiyizhen.handheld.component.message.bean.MarkReadReq;
import com.zhiyizhen.handheld.component.message.bean.MessageListBean;
import com.zhiyizhen.handheld.component.message.util.PageNavigationHelper;
import com.zhiyizhen.handheld.component.message.view.AboveAnchorPopupHelper;
import com.zhiyizhen.handheld.databinding.FragmentMessageBinding;
import com.zhiyizhen.handheld.net.ServiceFactory;
import com.zhiyizhen.handheld.net.response.ResponseData;
import com.zhiyizhen.handheld.net.response.ResponseObserver;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class MessageFragment extends BaseFragment implements PageNavigationHelper.OnPageSelectedListener {
    private FragmentMessageBinding binding;
    private RecyclerView mRecyclerView;
    private MessageAdapter adapter;
    private LoginBean loginBean;
    private PageNavigationHelper pageHelper;
    private int pageNo = 1;
    private int pageSize = 10;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = FragmentMessageBinding.inflate(inflater, container, false);
        return binding.getRoot();
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        loginBean = DataCache.getLoginBean();
        initView();
    }

    private void initView() {
        mRecyclerView = binding.recyclerView;
        adapter = new MessageAdapter(getContext());
        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(layoutManager);
        mRecyclerView.setAdapter(adapter);

        adapter.setOnItemReadListener(data -> markRead(data.getNoticeId()));

        pageHelper = new PageNavigationHelper(
                getContext(),
                binding.llPageNumbers,
                binding.btnPrev,
                binding.btnNext,
                this
        );

        binding.deleteBtn.setOnClickListener(v -> {
            markDelete();
            binding.allSelectCheckbox.setChecked(false);
        });
        binding.readBtn.setOnClickListener(v -> {
            markRead(0);
            binding.allSelectCheckbox.setChecked(false);
        });
        binding.allReadBtn.setOnClickListener(v -> {
            markAllRead();
            binding.allSelectCheckbox.setChecked(false);
        });
        binding.pageSizeLayout.setOnClickListener(v -> showPopupAboveButton());

        binding.allSelectCheckbox.setOnCheckedChangeListener((buttonView, isChecked) -> {
            for (int i = 0; i < adapter.getData().size(); i++) {
                adapter.getData().get(i).setChecked(isChecked);
            }
            adapter.notifyDataSetChanged();

            if (isChecked) {
                binding.allSelectCheckbox.setText("取消全选");
            } else {
                binding.allSelectCheckbox.setText("全选");
            }
        });
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            getMessageList(pageNo, 10);
        }
    }

    private void showPopupAboveButton() {
        // 使用 helper 类显示PopupWindow在按钮正上方
        PopupWindow popupWindow = AboveAnchorPopupHelper.showAboveAnchor(
                getContext(),
                binding.pageSizeLayout,
                R.layout.popup_page_size_select // PopupWindow的布局
        );

        View contentView = popupWindow.getContentView();
        TextView pageSize10 = contentView.findViewById(R.id.pageSize10);
        pageSize10.setOnClickListener(v -> {
            pageSize = 10;
            pageNo = 1;
            getMessageList(pageNo, pageSize);
            binding.pageSizeTv.setText(pageSize10.getText());
            popupWindow.dismiss(); // 关闭PopupWindow
        });
        TextView pageSize20 = contentView.findViewById(R.id.pageSize20);
        pageSize20.setOnClickListener(v -> {
            pageSize = 20;
            pageNo = 1;
            getMessageList(pageNo, pageSize);
            binding.pageSizeTv.setText(pageSize20.getText());
            popupWindow.dismiss(); // 关闭PopupWindow
        });
        TextView pageSize50 = contentView.findViewById(R.id.pageSize50);
        pageSize50.setOnClickListener(v -> {
            pageSize = 50;
            pageNo = 1;
            getMessageList(pageNo, pageSize);
            binding.pageSizeTv.setText(pageSize50.getText());
            popupWindow.dismiss(); // 关闭PopupWindow
        });
    }

    @Override
    public void onPageSelected(int page) {
        pageNo = page;
        getMessageList(pageNo, pageSize);
    }

    private void getMessageList(int page, int pageSize) {
        binding.allSelectCheckbox.setChecked(false);
        ServiceFactory.getService(IMessageService.class)
                .getNoticeList(loginBean.getToken(), loginBean.getClinicId(), page, pageSize)
                .compose(RxJavaUtil.mainSchedulers())
                .as(this.bindLifecycle())
                .subscribe(new ResponseObserver<>() {
                    @Override
                    protected void onSuccess(ResponseData<MessageListBean> responseData) {
                        if (responseData != null && responseData.getData() != null) {
                            setData(responseData.getData());
                            int totalCount = responseData.getData().getTotalCount();
                            int totalPageCount = (totalCount + pageSize - 1) / pageSize;
                            pageHelper.init(totalPageCount, pageNo);

                            if (totalCount > 0) {
                                binding.emptyView.setVisibility(View.GONE);
                                binding.messageLayout.setVisibility(View.VISIBLE);
                            } else {
                                binding.emptyView.setVisibility(View.VISIBLE);
                                binding.messageLayout.setVisibility(View.GONE);
                            }
                        } else {
                            binding.emptyView.setVisibility(View.VISIBLE);
                            binding.messageLayout.setVisibility(View.GONE);
                        }
                    }
                });
    }

    private void markRead(int id) {
        MarkReadReq markReadReq = new MarkReadReq();
        List<Integer> ids = new ArrayList<>();
        if (id <= 0) {
            for (int i = 0; i < adapter.getData().size(); i++) {
                if (adapter.getData().get(i).isChecked()) {
                    ids.add(adapter.getData().get(i).getNoticeId());
                }
            }
        } else {
            ids.add(id);
        }
        markReadReq.setIds(ids);
        ServiceFactory.getService(IMessageService.class)
                .markRead(loginBean.getToken(), loginBean.getClinicId(), markReadReq)
                .compose(RxJavaUtil.mainSchedulers())
                .as(this.bindLifecycle())
                .subscribe(new ResponseObserver<>() {
                    @Override
                    protected void onSuccess(ResponseData<String> responseData) {
                        for (int i = 0; i < adapter.getData().size(); i++) {
                            for (int j = 0; j < ids.size(); j++) {
                                if (Objects.equals(adapter.getData().get(i).getNoticeId(), ids.get(j))) {
                                    adapter.getData().get(i).setIsRead("1");
                                    adapter.getData().get(i).setChecked(false);
                                }
                            }
                        }
                        adapter.notifyDataSetChanged();
                        if (id <= 0) {
                            ToastUtil.showShort("操作成功");
                        }
                        EventBus.getDefault().post(new UpdateMessageCountEvent());
                    }
                });
    }

    private void markDelete() {
        MarkReadReq markReadReq = new MarkReadReq();
        List<Integer> ids = new ArrayList<>();
        for (int i = 0; i < adapter.getData().size(); i++) {
            if (adapter.getData().get(i).isChecked()) {
                ids.add(adapter.getData().get(i).getNoticeId());
            }
        }
        markReadReq.setIds(ids);

        ServiceFactory.getService(IMessageService.class)
                .markDelete(loginBean.getToken(), loginBean.getClinicId(), markReadReq)
                .compose(RxJavaUtil.mainSchedulers())
                .as(this.bindLifecycle())
                .subscribe(new ResponseObserver<>() {
                    @Override
                    protected void onSuccess(ResponseData<String> responseData) {
                        ToastUtil.showShort("操作成功");
                        getMessageList(pageNo, pageSize);
                        EventBus.getDefault().post(new UpdateMessageCountEvent());
                    }
                });
    }
    private void markAllRead() {
        ServiceFactory.getService(IMessageService.class)
                .markAllRead(loginBean.getToken(), loginBean.getClinicId())
                .compose(RxJavaUtil.mainSchedulers())
                .as(this.bindLifecycle())
                .subscribe(new ResponseObserver<>() {
                    @Override
                    protected void onSuccess(ResponseData<String> responseData) {
                        for (int i = 0; i < adapter.getData().size(); i++) {
                            adapter.getData().get(i).setIsRead("1");
                        }
                        adapter.notifyDataSetChanged();
                        ToastUtil.showShort("操作成功");
                        EventBus.getDefault().post(new UpdateMessageCountEvent());
                    }
                });
    }

    @SuppressLint("DefaultLocale")
    private void setData(MessageListBean bean) {
        adapter.setData(bean.getList());
        binding.totalCountTv.setText(String.format("共%1d条数据", bean.getTotalCount()));
    }
}
